import React,{FC, useEffect, useState} from "react";
import { Pagination } from "antd";
import {useSearchParams,useNavigate,useLocation} from 'react-router-dom'
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_PAGE, LIST_SEARCH_PARAM_PAGESIZE } from "../constant";
type PropsType={
    total:number,
}
const ListPage:FC<PropsType>=(props:PropsType)=>{
    const {total}=props
    const [current,setCurrent]=useState(1)
    const [pageSize,setPageSize]=useState(LIST_PAGE_SIZE)

    //从URL 参数中找到page pageSize,并且同步到Pagination组件中 
    const [searchParams]=useSearchParams()
    useEffect(()=>{
        const page=parseInt(searchParams.get(LIST_SEARCH_PARAM_PAGE)||'')||1
        const pageSize=parseInt(searchParams.get(LIST_SEARCH_PARAM_PAGESIZE)||'')||10
        setPageSize(pageSize)
        setCurrent(page)
    },[searchParams])
    //页码改变 切换参数
    const nav=useNavigate()
    const {pathname}= useLocation()
    function handlePageChange(page:number,pageSize:number){
        searchParams.set(LIST_SEARCH_PARAM_PAGE,page.toString())
        searchParams.set(LIST_SEARCH_PARAM_PAGESIZE,pageSize.toString())
        nav({
            pathname,
            search:searchParams.toString() //除了page pagesize 其他的URL参数要带着

        })
    }
    return <Pagination current={current} total={total} pageSize={pageSize} onChange={handlePageChange}/>
}
export default ListPage